#!/usr/bin/perl -w

BEGIN
{
	sub getPoints{return '../../' if (!$_[1]);return '../' if (!$_[0]);return '/';}
	(my $file = __FILE__) =~ s/\/?(modules\/)?(http_top\/)?(\w+\.pl)$/&getPoints($1,$2)/e;
	unshift(@INC, $file.'bin');
	unshift(@INC, $file.'modules/http_logging');
}

use strict;
use TWM;
use Logging;

populateCfromConfig('http_logging');
my $logging = new Logging;
my $squid_settings = $logging->getSquidsSettings();

my $is_sarg_running = `$ck{ps} ax|$ck{grep} -v 'grep'|$ck{grep} -c $C->{http_logging}->{sarg}`;
chomp $is_sarg_running;
if ($is_sarg_running ne '0') { print "running sarg process has been found. script terminated.\n"; exit 0 }

foreach my $v (values %$squid_settings)	{
	my ($month,$mday,$year);
	my ($month2,$mday2,$year2) = (((localtime(time))[4]+1),(localtime(time))[3],(localtime(time))[5]+1900);
	$mday2 =~ s/^(\d)$/0$1/;
	$month2 =~ s/^(\d)$/0$1/;

	my (@content4print,@content4mail,@ips,@logdirs_sorted);
	my $log_folder = $v->{log_folder};
	my $access_log = $v->{access_log};
	my $isp = $v->{isp};
	my $enabled = $v->{enabled};
	my @isp = split(/\|{1,3}/, $ck{ifaces});
	my $server_ip = $isp[2];
	my $server_name = getIPInfo($isp[2])->{'dns_name'}.".".$ck{'_domain_name'};

	my @input_sorted = map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [ $_, -M ] } <$ck{twmfolder}modules/$mc/logs/$isp/*>;

	foreach(@input_sorted) { 
		if (/^\/.+\/\d{4}\w{3}\d{2}-\d{4}\w{3}\d{2}$/) { 
			push(@logdirs_sorted,$_);
		}
	}

	if (scalar(@logdirs_sorted))
	{
		my $mtime = (stat $logdirs_sorted[0])[9];
		my @time = localtime($mtime);
		($month,$mday,$year) = ($time[4]+1,$time[3],1900 + $time[5]);
		$month =~ s/^(\d)$/0$1/;
		$mday =~ s/^(\d)$/0$1/;
	}
	else
	{
		$month = $month2 - 1;
		$year = $year2;
		$mday = '01';
		if ($month eq '0')
		{
			$month = 12;
			$year = $year - 1;
		}
		$month =~ s/^(\d)$/0$1/;
	}
#next if $isp ne 'Atlant';

	if ($enabled) {

		my $date4email = "$mday/$month/$year-$mday2/$month2/$year2";
		toDebugLog("$ck{nice} -n 19 $C->{http_logging}->{sarg} -x -n  -f $C->{http_logging}->{sarg_conf} -d $mday/$month/$year-$mday2/$month2/$year2 -l $log_folder/$access_log -o $ck{twmfolder}modules/$mc/logs/$isp > $C->{http_logging}->{sarg_log}");
#$mday/$month/$year-$mday2/$month2/$year2
#20/06/2011-21/06/2011
		system "$C->{http_logging}->{sarg} -x -n -f $C->{http_logging}->{sarg_conf} -d $mday/$month/$year-$mday2/$month2/$year2 -l $log_folder/$access_log -o $ck{twmfolder}modules/$mc/logs/$isp > $C->{http_logging}->{sarg_log}";
#next;
		$month = ('','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec')[$month];
		$month2 = ('','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec')[$month2];
		my ($index_file, $dt);
        
		opendir(DIR, "$ck{twmfolder}modules/$mc/logs/$isp") || die "Can't open $ck{twmfolder}modules/$mc/logs/$isp: $!\n";
		foreach (readdir(DIR))
		{
			if (/^$year$month\d{2}-$year2$month2\d{2}$/)
			{
				$index_file = "$ck{twmfolder}modules/$mc/logs/$isp/$_/index.html";
				$dt = $_;
			}
		}
		closedir DIR;
#print "read $index_file\n";

		if (($index_file) && (-e $index_file))	{
        
			local $/ = '';
                
			open(FILE,"+<$index_file") || toErrorLog("Can't open $index_file: $!",1);
			my $f = <FILE>;
                
			$f =~ s/^<tr><th class="logo">.+Topuser Report<\/td><\/tr>\n<\/table><\/center>$//ms;
			$f =~ s/(?<=^<center><table cellpadding="1" cellspacing="2">\n)<tr><td><br><\/td><td><\/td><\/tr>.+Downloads.+Report.+\n<tr><td><\/td><\/tr>\n//ms;
			$f =~ s/Generated by <a.+<\/a> on/Generated at/;
                
			@ips = ($f =~ /^.+=["'](\d{1,3}[._]\d{1,3}[._]\d{1,3}[._]\d{1,3})\/d.+$/mg);
                
			$f =~ s/(<img src=["'])../$1\/modules\/$mc/g;
			$f =~ s/<a href=["'](\d{1,3}[._]\d{1,3}[._]\d{1,3}[._]\d{1,3}\/graph_day\.png)["']>/<a href='sarg_img.pl?squid=$isp&dt=$dt&fl=$1'>/g;
			$f =~ s/<a href=["']((\w{6}|\w{8})\.html)["']>/<a href="sarg_rpt.pl?squid=$isp&dt=$dt&fl=$1">/g;
			$f =~ s/<a href=["']\d{1,3}[._]\d{1,3}[._]\d{1,3}[._]\d{1,3}\/(d?\d{1,3}[._]\d{1,3}[._]\d{1,3}[._]\d{1,3})\.html["']>/<a href='sarg_rpt.pl?squid=$isp&dt=$dt&fl=$1'>/g;
			push (@content4print, $f);
			
			$f =~ s/<img src="\/modules\/http_top\/images\//<img src="http:\/\/$server_name:$ck{httpd_port}\/modules\/http_top\/images\//g;
			$f =~ s/<a href=["'](sarg_img.pl|sarg_rpt.pl)\?squid=$isp&dt=/<a href='http:\/\/$server_name:$ck{httpd_port}\/cgi-bin\/modules\/$mc\/$1\?squid=$isp&dt=/g;
			push (@content4mail, $f);
                
			seek(FILE,0,0) || toErrorLog("Seeking $index_file: $!",1);
			print FILE foreach @content4print;
			truncate(FILE, tell(FILE)) || toErrorLog("Truncating $index_file: $!",1);
			close(FILE) || toErrorLog("Can't close $index_file: $!",1);
                
			my $ip_list = &getIPs;
        
			foreach (@ips)	{
				my ($ip,$full_name) = ($_,'');
				$ip =~ s/_/./g;
				foreach (@$ip_list) {
					if ($_->{ip} eq $ip) {
						$full_name = $_->{full_name};
						last;
					}
    	    	    	    	}
				my $ipstring = "<tr><td class=\"header\" colspan=\"2\">ip:&nbsp;$ip</td></tr>\n";
				{
					my @content4print;
					my $in="$ck{twmfolder}modules/$mc/logs/$isp/$dt/$_/$_\.html";
					open(FILE, "+<$in") || toErrorLog("Can't open $in: $!",1);
					my $f = <FILE>;
					$f =~ s/^[<>\w\s]+="logo">.+\n//m;
					$f =~ s/^[<>\s\w]+="title".+\n(.+\n[<>\s\w]+="header".+;)([\w\W]+?)(<.+\n).+\n.+\n.+\n/$1$2 \($full_name\)$3${ipstring}/mg;
				    	$f =~ s/Generated by <a.+<\/a> on/Generated at/;
				    	$f =~ s/(<img src=["'])..\/../$1\/modules\/$mc/g;
				    	$f =~ s/<a href=["'](tt.+\.html)["']>/<a href="sarg_rpt.pl?squid=$isp&dt=$dt&fl=$1">/g;
					push(@content4print,$f);
					seek(FILE,0,0) || toErrorLog("Seeking $in: $!",1);
					print FILE foreach @content4print;
					truncate(FILE, tell(FILE)) || toErrorLog("Truncating $in: $!",1);
					close(FILE) || toErrorLog("Can't close $in: $!",1);
				}
                
				{
					my @content4print;
    	    	    	    		my $in="$ck{twmfolder}modules/$mc/logs/$isp/$dt/$_/d$_\.html";
					open(FILE, "+<$in") || toErrorLog("Can't open $in: $!",1);
					my $f = <FILE>;
					$f =~ s/^[<>\w\s]+="logo">.+\n//m;
					$f =~ s/.+\n[<>\w\s]+="title"\s.+\n.+\n//;
					$f =~ s/^(<.+>User\:.+?\;)([\d\.]+?)(<.+\n)/$1$full_name$3${ipstring}/m;
#					$f =~ s/^([<>\w\s"=]+User[^;]+?;)(\w+)(<.+\n)/$1$2$3${ipstring}/m;
#					$f =~ s/$2/$full_name}/;
					$f =~ s/Generated by <a.+<\/a> on/Generated at/;
					push(@content4print,$f);
					seek(FILE,0,0) || toErrorLog("Seeking $in: $!",1);
					print FILE foreach @content4print;
					truncate(FILE, tell(FILE)) || toErrorLog("Truncating $in: $!",1);
					close(FILE) || toErrorLog("Can't close $in: $!",1);
				}
                
				my @ttlist = glob("$ck{twmfolder}modules/$mc/logs/$isp/$dt/$_/tt*.html");
				foreach(@ttlist) {
					my @content4print;
					open(FILE, "+<$_") || toErrorLog("Can't open $_: $!",1);
					my $f = <FILE>;
					$f =~ s/^[<>\w\s]+="logo">.+\n//m;
					$f =~ s/(?<=<table>\n)[<>\s\w]+="title".+\n(.+\n[<>\s\w]+="header".+;)([\w\W]+?)(<.+\n).+\n.+\n/$1${full_name}$3${ipstring}/m;
					push(@content4print,$f);
					seek(FILE,0,0) || toErrorLog("Seeking $_: $!",1);
					print FILE foreach @content4print;
					truncate(FILE, tell(FILE)) || toErrorLog("Truncating $_: $!",1);
					close(FILE) || toErrorLog("Can't close $_: $!",1);
				}
                
                
			}
        
		}
		else {
			push(@content4mail, "Hello<p>HTTP wasn't used by <b>$isp</b> ISP during $date4email.");
		}

		if ($cm{email_monthly_log}) {
        
			my $report = join("",@content4mail)."\n";
                	my $subj = $cm{subject};
			$subj =~ s/\[ISP\]/\[$isp\]/;
        
			send_email(
				{
					'from' => $ck{sender},
					'to' => 'vhornik@gmail.com', #$cm{email_to},
					'ctype' => 'text/html',
					'subject' => $subj,
               	    		'body' => $report
		        	}
			)
		}
	}
}

__END__

